package com.kool.leitu.filter;

import com.alibaba.fastjson.JSONObject;
import com.kool.constant.ReqAuthEnum;
import com.kool.constant.ReqSignatureEnum;
import com.kool.leitu.base.exception.AppException;
import com.kool.leitu.base.util.PropertyUtils;
import com.kool.leitu.base.util.SecurityUtils;
import com.kool.leitu.base.util.StringUtils;
import com.kool.leitu.bean.ReqBean;
import com.kool.leitu.dao.ReqDao;
import com.kool.user.bean.vo.UserInfoVo;
import com.kool.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description:
 * @author: tianhe
 * @create: 2019/02/02 13:32
 */
@Slf4j
@Component
public class GlobalInterceptor implements HandlerInterceptor {
    @Autowired
    private ReqDao reqDao;
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String test = request.getParameter("test");
        if (StringUtils.isNotEmpty(test)) {
            return true;
        }
        String url = request.getParameter("url");
        String loginName = request.getParameter("loginName");
        String time = request.getParameter("time");
        String source = request.getParameter("source");
        String token = request.getParameter("token");
        String sign = request.getParameter("sign");
        String ip = getIpAdrress(request);

        String uri = request.getRequestURI();
        if (StringUtils.isEmpty(url)) {
            url = uri;
        }

        // 请求日志
        JSONObject logs = new JSONObject();
        logs.put("token", token);
        logs.put("url", url);
        logs.put("loginName", loginName);
        logs.put("time", time);
        logs.put("source", source);
        logs.put("ip", ip);
        log.info(logs.toJSONString());

//        ReqBean req = reqDao.selectByUrl(url);
//
//        if (null == req) {
//            throw new RuntimeException("非法请求URL:" + url);
//        }
//        //请求是否需要验签
//        if (ReqSignatureEnum.SIGNATURE_TRUE.getCode().equals(req.getIsSignature())) {
//            // 取用户信息
//            UserInfoVo userInfoVo = userService.getUserInfo(loginName);
//            //验token
//            String vToken = userInfoVo.getToken();
//            if (!vToken.equals(token)) {
//                response.sendError(401);
//                return false;
//            }
//
//            // 验签
//            String vSign = SecurityUtils
//                    .sha(url + "&" + loginName + "&" + time + "&" + source + "&" + token);
//            if (vSign.equals(sign) == false) {
//                response.sendError(401);
//                return false;
//            }
//        }
//
//        //请求是否需要鉴权
//        if (ReqAuthEnum.AUTH_TRUE.getCode().equals(req.getIsAuth())) {
//            if (!auth(loginName, url)) {
//                response.sendError(403);
//                return false;
//            }
//        }

        return true;
    }

    /**
     * 鉴权
     *
     * @param loginName
     * @param url
     * @return
     */
    private boolean auth(String loginName, String url) {
        //todo
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        if (e instanceof AppException) {
            log.info("业务异常：{}",e.getMessage());
        }
    }


    /**
     * @param request
     * @return
     * @DESCRIBE 取请求方ip地址
     * @DATE 2018年7月13日 下午9:52:54
     */
    private String getIpAdrress(HttpServletRequest request) {
        String Xip = request.getHeader("X-Real-IP");
        String XFor = request.getHeader("X-Forwarded-For");
        if (StringUtils.isEmpty(XFor) == false && !"unKnown".equalsIgnoreCase(XFor)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = XFor.indexOf(",");
            if (index != -1) {
                return XFor.substring(0, index);
            } else {
                return XFor;
            }
        }
        XFor = Xip;
        if (StringUtils.isEmpty(XFor) == false && !"unKnown".equalsIgnoreCase(XFor)) {
            return XFor;
        }
        if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getRemoteAddr();
        }
        return XFor;
    }

}
